package com.nx.platform.es.common.utils;

import com.google.common.base.Enums;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author
 * @date 2018/04/16
 */
public enum IdSharding {

    NULL {
        @Override
        public @NotNull String sharding(@NotNull Long id) {
            return "default";
        }
    },

    INFO {
        @Override
        public @NotNull String sharding(@NotNull Long id) {
            return (((id >>> 18) & 15) + 1L) + "-" + (((id >>> 14) & 15) + 1);
        }
    },

    ORDERID {
        @Override
        public @NotNull String sharding(@NotNull Long id) {
            return (id >> 14 & 0xff % 8) + "";
        }
    };

    public static @NotNull IdSharding get(@Nullable String idSharding) {
        return Enums.getIfPresent(IdSharding.class, Strings.nullToEmpty(idSharding)).or(IdSharding.NULL);
    }

    public abstract @NotNull String sharding(@NotNull Long id);

    public List<Collection<Long>> shardingAndPartition(Collection<Long> collection, int size) {
        return collection.stream()
                .collect(Collectors.groupingBy(this::sharding)).values().stream()
                .flatMap(list -> Lists.partition(list, size).stream())
                .collect(Collectors.toList());
    }

}
